<!-- src/components/MyComponent.vue -->
<template>
  <q-page padding>
    <div class="container layout">
      <!-- Left Side: Input Fields -->
      <div class="left-side">
        <div class="input-group">
          <label for="我的行业">我的行业:</label>
          <q-input
            type="textarea"
            ref="我的行业"
            v-model="myIndustry"
            @focus="onFocus"
            rows="6"
            auto-grow
          />
        </div>
        <div class="input-group">
          <label for="前三大客户">前三大客户:</label>
          <q-input
            type="textarea"
            ref="前三大客户"
            v-model="topCustomers"
            @focus="onFocus"
            rows="6"
            auto-grow
          />
        </div>
        <div class="input-group">
          <label for="我能提供的身边资源">我能提供的身边资源:</label>
          <q-input
            type="textarea"
            ref="我能提供的身边资源"
            v-model="resources"
            @focus="onFocus"
            rows="6"
            auto-grow
          />
        </div>
        <div class="input-group">
          <label for="和我有相同客户的行业">和我有相同客户的行业:</label>
          <q-input
            type="textarea"
            ref="和我有相同客户的行业"
            v-model="similarIndustry"
            @focus="onFocus"
            rows="6"
            auto-grow
          />
        </div>
        <div class="input-group">
          <label for="和我有相同客户的行业(分会已有)"
            >和我有相同客户的行业(分会已有):</label
          >
          <q-input
            type="textarea"
            ref="和我有相同客户的行业(分会已有)"
            v-model="similarIndustryExisting"
            @focus="onFocus"
            rows="6"
            auto-grow
          />
        </div>
      </div>

      <!-- Right Side: Charts -->
      <div class="right-side">
        <div class="chart" ref="main-sunburst"></div>
        <div class="chart" ref="main-net"></div>
        <div class="chart" ref="word-cloud"></div>
      </div>
    </div>
  </q-page>
</template>

<script>
import * as echarts from "echarts";
import "echarts-wordcloud";

export default {
  data() {
    return {
      myIndustry: "",
      topCustomers: "",
      resources: "",
      similarIndustry: "",
      similarIndustryExisting: "",
      currentInput: null,
    };
  },
  methods: {
    onFocus(event) {
      this.currentInput = event.target;
    },
    generateNetData(root) {
      let nodes = [{ name: root.name, symbolSize: 80 }];
      let links = [];

      root.children.forEach((child, idx) => {
        child.children.forEach((subchild) => {
          nodes.push({
            name: subchild.name,
            symbolSize: 80,
            itemStyle: { color: colors[idx] },
          });
          links.push({
            source: root.name,
            target: subchild.name,
            lineStyle: { color: colors[idx] },
          });
        });
      });

      return { nodes, links };
    },
    generateData() {
      let root = {
        name: this.$refs["我的行业"].value,
        children: [],
      };

      let ids = [
        "前三大客户",
        "我能提供的身边资源",
        "和我有相同需求客户的行业(分会已有)",
        "和我有相同需求客户的行业",
      ];
      ids.forEach((id, idx) => {
        if (!this.$refs[id].value) {
          return;
        }
        // 加入idx，用于颜色数组的索引
        let input = this.$refs[id].value.split(",");
        if (input.length && input[0]) {
          root.children.push({
            name: id,
            itemStyle: {
              color: colors[idx], // 指定二级数据的颜色
            },
            children: input.map((item) => {
              return {
                name: item,
                value: 1,
                itemStyle: {
                  color: colors[idx], // 指定三级数据的颜色
                },
              };
            }),
          });
        }
      });

      return [root];
    },
    removeDuplicate(el) {
      let list = el.value.split(",");
      let mapping = {};
      let result = [];
      list.forEach((item) => {
        if (!mapping[item]) {
          mapping[item] = 1;
          result.push(item);
        }
      });

      el.value = result.join(",");
      return el.value;
    },
    // Add your other methods here
  },
  mounted() {
    let currentInput = {};

    let sunburstChart = echarts.init(this.$refs["main-sunburst"]);
    let netChart = echarts.init(this.$refs["main-net"]);

    let textareas = document.querySelectorAll("textarea");

    // 定义一个onFocus方法
    function onFocus(event) {
      // 在这里编写你的onFocus逻辑
      // console.log('Textarea focused:', event.target.id);
      currentInput = event.target;
    }

    // 为每个textarea元素添加onFocus监听事件
    textareas.forEach(function (textarea) {
      textarea.addEventListener("focus", onFocus);
    });

    document.body.addEventListener("input", (event) => {
      let sunburstData = this.generateData();
      let netData = this.generateNetData(sunburstData[0]);

      sunburstChart.setOption({
        series: {
          type: "sunburst",
          data: sunburstData,
          radius: [0, "90%"],
          label: {
            rotate: 0, // 0 度即水平显示
            align: "center",
            verticalAlign: "middle",
          },
        },
      });

      netChart.setOption({
        series: [
          {
            type: "graph",
            layout: "force",
            data: netData.nodes,
            links: netData.links,
            roam: true,
            label: {
              position: "inside",
              formatter: "{b}",
              show: true,
              fontSize: 20,
            },
            force: {
              repulsion: 1000,
              edgeLength: [100, 150],
            },
          },
        ],
      });
    });

    // 初始加载示例数据
    document.body.dispatchEvent(new Event("input"));

    // 初始化ECharts实例
    let cloudchart = echarts.init(this.$refs["word-cloud"]);

    let cloudwordData = [
      { name: "Hello", value: 10000 },
      { name: "World", value: 6181 },
      { name: "ECharts", value: 4386 },
      { name: "WordCloud", value: 8482 },
      //...其他数据
    ];
    let colors = ["#FF6F61", "#6B5B95", "#88B04B", "#FFD700"];

    // 定义图表的配置项
    let option = {
      series: [
        {
          type: "wordCloud",
          gridSize: 20,
          sizeRange: [12, 50],
          rotationRange: [0, 0],
          shape: "circle",
          width: 500,
          height: 500,
          drawOutOfBound: true,
          textStyle: {
            normal: {
              color: function () {
                return (
                  "rgb(" +
                  [
                    Math.round(Math.random() * 160),
                    Math.round(Math.random() * 160),
                    Math.round(Math.random() * 160),
                  ].join(",") +
                  ")"
                );
              },
            },
            emphasis: {
              shadowBlur: 10,
              shadowColor: "#333",
            },
          },
          data: cloudwordData,
        },
      ],
    };

    // 使用刚指定的配置项和数据显示图表
    cloudchart.setOption(option);

    cloudchart.on("click", function (params) {
      // 获取被点击的词条
      let word = params.name;
      console.log(word);
      // 将词条设置为输入框的值
      if (!currentInput.value) {
        currentInput.value += word;
      } else {
        currentInput.value += "," + word;
      }
      this.removeDuplicate(currentInput);
    });
  },
};
</script>
<style>
body,
html {
  height: 100%;
  margin: 0;
  font-family: Arial, sans-serif;
}

.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
  margin-top: 50px;
}

.input-group {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  /* 靠右对齐 */
  width: 300px;
  /* 为了给输入框和标签提供足够的空间 */
  gap: 10px;
}

input[type="button"] {
  padding: 10px 20px;
  font-size: 1rem;
  cursor: pointer;
}

label {
  flex-shrink: 0;
  width: 150px;
  /* 设置一个固定的宽度 */
  text-align: right;
  /* 标签内的文字靠右对齐 */
  margin-right: 10px;
}

textarea {
  width: 200px;
}

/* 标签样式可以在这里定义 */
.tag {
  background-color: #007bff;
  color: #fff;
  padding: 5px 10px;
  margin-right: 5px;
  border-radius: 5px;
}

/**/

.layout {
  display: flex;
  justify-content: space-between;
  height: 100vh;
}

.left-side {
  flex: 1;
  padding: 20px;
}

.right-side {
  flex: 1;
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
  /* Provide some spacing between the charts */
}

.chart {
  flex: 1;
  border: 1px solid #ccc;
  /* Optional: To visualize the chart's boundaries */
}

.chart-container {
  height: 300px;
  width: 100%;
  margin-bottom: 20px;
}
</style>
